package org.springblade.modules.admin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springblade.common.cache.SysCache;
import org.springblade.common.constant.TenantConstant;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.tenant.BladeTenantProperties;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.jackson.JsonUtil;
import org.springblade.core.tool.utils.DesUtil;
import org.springblade.core.tool.utils.DigestUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.admin.dto.UserDTO;
import org.springblade.modules.admin.entity.MaintainSignSeting;
import org.springblade.modules.admin.entity.UserExt;
import org.springblade.modules.admin.service.*;
import org.springblade.modules.admin.vo.UserExtVO;
import org.springblade.modules.system.entity.Tenant;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.entity.UserDept;
import org.springblade.modules.system.mapper.UserMapper;
import org.springblade.modules.system.service.IRoleService;
import org.springblade.modules.system.service.IUserDeptService;
import org.springblade.modules.system.service.IUserOauthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Date: 2020/12/24 3:31 下午
 * @Author: Jackey
 * @Description: BuildingServiceImpl
 */
@Service
public class AccountManageServiceImpl extends BaseServiceImpl<UserMapper, User> implements AccountManageService {

	@Autowired
	private IUserDeptService userDeptService;
	@Autowired
	private IUserOauthService userOauthService;
	@Autowired
	private IRoleService roleService;
	@Autowired
	private BladeTenantProperties tenantProperties;
	@Autowired
	private UserExtService userExtService;
	@Autowired
	private MaintainSignSetingService maintainSignSetingService;
	@Autowired
	private UserSignDetailService userSignDetailService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean submit(UserDTO userDTO) {
		if (StringUtil.isBlank(userDTO.getTenantId())) {
			userDTO.setTenantId(BladeConstant.ADMIN_TENANT_ID);
		}
		String tenantId = userDTO.getTenantId();
		Tenant tenant = SysCache.getTenant(tenantId);
		if (Func.isNotEmpty(tenant)) {
			Integer accountNumber = tenant.getAccountNumber();
			if (tenantProperties.getLicense()) {
				String licenseKey = tenant.getLicenseKey();
				String decrypt = DesUtil.decryptFormHex(licenseKey, TenantConstant.DES_KEY);
				accountNumber = JsonUtil.parse(decrypt, Tenant.class).getAccountNumber();
			}
			Integer tenantCount = baseMapper.selectCount(Wrappers.<User>query().lambda().eq(User::getTenantId, tenantId));
			if (accountNumber != null && accountNumber > 0 && accountNumber <= tenantCount) {
				throw new ServiceException("当前租户已到最大账号额度!");
			}
		}
		if (Func.isNotEmpty(userDTO.getPassword())) {
			userDTO.setPassword(DigestUtil.encrypt(userDTO.getPassword()));
		}
		Integer userCount = baseMapper.selectCount(Wrappers.<User>query().lambda().eq(User::getTenantId, tenantId).eq(User::getAccount, userDTO.getAccount()));
		if (userCount > 0 && Func.isEmpty(userDTO.getId())) {
			throw new ServiceException(StringUtil.format("当前用户 [{}] 已存在!", userDTO.getAccount()));
		}
		Integer phoneCount = baseMapper.selectCount(Wrappers.<User>lambdaQuery().eq(User::getTenantId, tenantId).eq(User::getPhone, userDTO.getPhone()));
		if (phoneCount > 0) {
			throw new ServiceException("手机号码已被使用!");
		}
		save(userDTO);
		submitUserDept(userDTO);
		//关联用户扩展表
		UserExt userExt = new UserExt();
		userExt.setUserId(userDTO.getId());
		if (ObjectUtil.isNotNull(userDTO.getMaintainCompanyId())) {
			userExt.setMaintainCompanyId(userDTO.getMaintainCompanyId());
		}
		if (ObjectUtil.isNotNull(userDTO.getEstateCompanyId())) {
			userExt.setEstateCompanyId(userDTO.getEstateCompanyId());
		}
//		if (ObjectUtil.isNotNull(userDTO.getMaintainGroupId())) {
//			userExt.setMaintainGroupId(userDTO.getMaintainGroupId());
//			//查询用户所在组是否有签到配置 有则加入
//			MaintainSignSeting maintainSignSeting = maintainSignSetingService.getOne(
//				Wrappers.<MaintainSignSeting>lambdaQuery().eq(MaintainSignSeting::getGroupId, userDTO.getMaintainGroupId()), false);
//			if (ObjectUtil.isNotNull(maintainSignSeting)) {
//				MaintainSignSeting userSignSetting = new MaintainSignSeting();
//				userSignSetting.setUserId(userDTO.getId());
//				userSignSetting.setGroupId(userDTO.getMaintainGroupId());
//				userSignSetting.setSignDate(maintainSignSeting.getSignDate());
//				userSignSetting.setSignOutDate(maintainSignSeting.getSignOutDate());
//				maintainSignSetingService.save(userSignSetting);
//				//生成考勤记录
//				userSignDetailService.insertBatch(userSignSetting.getId(), userSignSetting.getUserId(), userSignSetting.getGroupId(), new Date(), userSignSetting.getTenantId());
//			}
//		}

		return userExtService.save(userExt);

	}

	private boolean submitUserDept(User user) {
		List<Long> deptIdList = Func.toLongList(user.getDeptId());
		List<UserDept> userDeptList = new ArrayList<>();
		deptIdList.forEach(deptId -> {
			UserDept userDept = new UserDept();
			userDept.setUserId(user.getId());
			userDept.setDeptId(deptId);
			userDeptList.add(userDept);
		});
		userDeptService.remove(Wrappers.<UserDept>update().lambda().eq(UserDept::getUserId, user.getId()));
		return userDeptService.saveBatch(userDeptList);
	}


//	@Override
//	public IPage<UserExtVO> selectUserPage(IPage<UserExtVO> page, User user, Integer roleType, String tenantId) {
////		List<Long> deptIdList = SysCache.getDeptChildIds(deptId);
////		List<Long> groupIds = maintainGroupService.getAllGroupId(user.getMaintainGroupId());
//		List<Long> groupIds = null;
//		return page.setRecords(this.baseMapper.selectUserExtPage(page, user, tenantId, roleType, groupIds));
//	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateUser(UserDTO user) {
		String tenantId = user.getTenantId();
		Integer userCount = baseMapper.selectCount(
			Wrappers.<User>query().lambda()
				.eq(User::getTenantId, tenantId)
				.eq(User::getAccount, user.getAccount())
				.notIn(User::getId, user.getId())
		);
		if (userCount > 0) {
			throw new ServiceException(StringUtil.format("当前用户 [{}] 已存在!", user.getAccount()));
		}

		User u = baseMapper.selectById(user.getId());
		if (!user.getPhone().equals(u.getPhone())) {
			Integer phoneCount = baseMapper.selectCount(Wrappers.<User>lambdaQuery().eq(User::getTenantId, tenantId).eq(User::getPhone, user.getPhone()));
			if (phoneCount > 0) {
				throw new ServiceException("手机号码已被使用!");
			}
		}

		updateUserInfo(user);
		submitUserDept(user);

		UserExt result = userExtService.getOne(new LambdaQueryWrapper<UserExt>().eq(UserExt::getUserId, user.getId()));
		//关联用户扩展表
		UserExt userExt = new UserExt();
		userExt.setId(result.getId());
		userExt.setUserId(user.getId());


		if (ObjectUtil.isNotNull(user.getMaintainCompanyId())) {
			userExt.setMaintainCompanyId(user.getMaintainCompanyId());
		}
		if (ObjectUtil.isNotNull(user.getEstateCompanyId())) {
			userExt.setEstateCompanyId(user.getEstateCompanyId());
		}
//		if (ObjectUtil.isNotNull(user.getMaintainGroupId())) {
//			userExt.setMaintainGroupId(user.getMaintainGroupId());
//			//查询用户所在组是否有签到配置 有则加入
//			MaintainSignSeting maintainSignSeting = maintainSignSetingService.getOne(
//				Wrappers.<MaintainSignSeting>lambdaQuery().eq(MaintainSignSeting::getGroupId, user.getMaintainGroupId()), false);
//			if (ObjectUtil.isNotNull(maintainSignSeting)) {
//				//查询用户是否已加入规则 有则修改
//				MaintainSignSeting userSignSetting = maintainSignSetingService.getOne(
//					Wrappers.<MaintainSignSeting>lambdaQuery().eq(MaintainSignSeting::getUserId, user.getId()));
//				if (ObjectUtil.isNotNull(userSignSetting)) {
//					userSignSetting.setGroupId(user.getMaintainGroupId());
//					maintainSignSetingService.updateById(userSignSetting);
//				} else {
//					userSignSetting = new MaintainSignSeting();
//					userSignSetting.setUserId(user.getId());
//					userSignSetting.setGroupId(user.getMaintainGroupId());
//					userSignSetting.setSignDate(maintainSignSeting.getSignDate());
//					userSignSetting.setSignOutDate(maintainSignSeting.getSignOutDate());
//					maintainSignSetingService.save(userSignSetting);
//				}
//				//生成考勤记录
//				userSignDetailService.insertBatch(userSignSetting.getId(), userSignSetting.getUserId(), userSignSetting.getGroupId(), new Date(), userSignSetting.getTenantId());
//			}
//		} else {
//			userExt.setMaintainGroupId(null);
//		}

		return userExtService.saveOrUpdate(userExt);
	}

	public boolean updateUserInfo(User user) {
		user.setPassword(null);
		return updateById(user);
	}
}


